<?php
class SiteAction extends CommonAction {
	
	public function update(){
		//写入语言配置
		$langList = M('Langconfig') -> where(array('langs_id' => $this->_post('lang_id'))) -> select();
		$sl = M('Sitelang');
		$sl -> where(array('site_id' => $this->_post('id'))) -> delete();
		foreach($langList as $k => $v){
			$data['key'] = $v['key'];
			$data['site_id'] = $this->_post('id');
			$data['val'] = $v['val'];
			$sl -> data($data) -> add();
		}
		
		
		//代理级别价格
		if(getAccessMenu($this->accessList, 'Admin', 'Agentlevel', 'index')){
			if($this->_post('agentlevelid')){
				$levelpricedb = M('Agentprice');
				foreach($this->_post('agentlevelid') as $k => $v){
					$levelprice = $levelpricedb -> where(array('siteid' => $this->_post('id'), 'agentlevel_id' => $_POST['agentlevelid'][$k])) -> find();
					$data['siteid'] = $this->_post('id');
					$data['price'] = $_POST['agentlevelprice'][$k];
					$data['agentlevel_id'] = $_POST['agentlevelid'][$k];
					
					if(!$levelprice){
					    //不存在，添加
						$levelpricedb -> data($data) -> add();
					}else{
						//存在记录，只做更新
						$levelpricedb -> where(array('id' => $levelprice['id'])) -> data($data) -> save();
					}
				}
			}
			//$this -> Agentlevel = M('Agentlevel') -> select();
		}
		
		if(session(C ( 'ADMIN_AUTH_KEY' ))){
			$_POST['timeout'] = strtotime($_POST['timeout']);
			$_POST['roleid'] = implode(',', $_POST['roleid']);
			parent::update();
		}else{
			unset($_POST['timeout']);
			parent::update();
		}
	}
	public function delete(){
		if(session(C ( 'ADMIN_AUTH_KEY' ))){
			$this->deleteSite($this->_get('id'));
			parent::delete();
		}else{
			$this->error('您没有权限删除站点');
		}
	}
	
	public function deleteSite($id){
		$db = M();
		$table = D('Manage_module') -> getAllTables();
		foreach($table as $v){
			$fieldlist = $db -> table($v) -> getDbFields();
			if(in_array('site_id', $fieldlist)){
				$db -> table($v) -> where(array('site_id' => array('in', $id))) -> delete();
			}
		}
	}
	
	
	//设置代理
	public function setagent(){
		if($this->_get('id')){
			$info = $this->dao -> where(array('id' => $this->_get('id'))) -> find();
			if($info['agent'] == 1){
				$data['agent'] = 0;
			}else{
				$data['agent'] = 1;
			}
			$ret = $this->dao -> data($data) -> where(array('id' => $this->_get('id'))) -> save();
			if($ret !== false){
				$this->success('操作成功');
			}else{
				$this -> error($this->dao -> getError());
			}
		}else{
			$this -> error('参数错误');
		}
	}
	
	function index(){
		//是否管理员
		if(session(C ( 'ADMIN_AUTH_KEY' ))){
			$this->listmap=1;
		}else{
			
	        $ret = D('User') -> getSiteList($this->UserInfo);
			$sids = array();
			$sids[] = 0;
			foreach($ret as $k => $v){
				if($v['id'] > 0){
					$sids[] = $v['id'];
				}
				
			}
			
			
			//获取所有站点ID
			$this->listmap="1 and s.id in(".implode(',', $sids).")";
		}
		

		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and s.title like '%{$keywords}%'";
			$this->keywords=$keywords;
		}
        parent::_list("s","left join __USER__ as u on u.id=s.uid left join __TEMPLATE__ t on t.id=s.template_id","s.*,u.account as loginName,u.nickname as nickname, t.title templateName");
		
		
		$list = $this->get('list');
		$site_userdb = M('Site_user');
		foreach($list as $k => $v){
			$list[$k]['userlist'] = $site_userdb -> alias('su') -> join("left join __USER__ AS u on u.id = su.user_id") -> where(array('su.site_id' => $v['id'])) -> Field('u.nickname,u.id') -> select();
			
		}
		
		$this->assign('list', $list); 
		if(isMobile()){
			$this->display('indexMobile');
		}else{
			$this->display();
		}
		

	}
	public function add(){
		if(session(C ( 'ADMIN_AUTH_KEY' ))){
		    $this->mySiteList=$this->dao->select();
		}else{
			$this->mySiteList=$this->dao->where(array('uid'=>$this->UserInfo))->select();
		}
		$memberTpl = MyScandir(TMPL_PATH.'Member/');
		unset($memberTpl[0]);
		unset($memberTpl[1]);
		$this->MEMBERDEFAULT_THEME = $memberTpl;
		parent::add();
	}
	public function edit(){
		if(session(C ( 'ADMIN_AUTH_KEY' ))){
		    $this->mySiteList=$this->dao->select();
		}else{
			$this->mySiteList=$this->dao->where(array('uid'=>$this->UserInfo))->select();
		}
		$memberTpl = MyScandir(TMPL_PATH.'Member/');
		unset($memberTpl[0]);
		unset($memberTpl[1]);
		$this->MEMBERDEFAULT_THEME = $memberTpl;
		//dump($this->MEMBERDEFAULT_THEME);
		$this->LangList = M('Langs') -> select();
		if(session(C('USER_AUTH_KEY') ) == 1){
			$this->role_list = M('Role')-> where(array('user_id' => session(C('USER_AUTH_KEY')))) -> select();
		}
		
		//代理级别
		if(getAccessMenu($this->accessList, 'Admin', 'Agentlevel', 'index')){
			$Agentlevel = M('Agentlevel') -> select();
			foreach($Agentlevel as $k => $v){
				$Agentlevel[$k]['price'] = M('Agentprice') -> where(array('agentlevel_id' => $v['id'],'siteid' => $this->_get('id'))) -> getField('price');
			}
			$this->assign('Agentlevel', $Agentlevel);
		}
		
		$info = $this->dao -> where(array('id' => $this->_get('id'))) -> find();
		$info['roleid'] = explode(',', $info['roleid']);
		$this->assign('info', $info);
		$this -> display();
	}
	public function insert(){
		$_POST['timeout']= strtotime($this->_post('timeout'));
		$_POST['uid']=$this->UserInfo;
		parent::insert();
	}
	
	//写配置项的值，打开配置页
	public function Conf(){
		if($this->_get('id')){
			$ConfList=$this->dao->alias("s")->join("left join __TEMPLATE__ as t on t.id=s.template_id")->where(array('s.id'=>$this->_get('id')))->Field("s.*,t.config as confList")->find();
			$this->setting_list=json_decode($ConfList['confList'],true);
			$this->id=isset($_GET['id'])?$this->_get('id'):$this->siteid;
			//多表存储扩展,提高效率
			$this->cur_setting = M('Setting_extends')->where(array('site_id'=>$this->id))->select();
			foreach($this->cur_setting as $k=>$v){
				
				
				
				$cur_setting[$v['name']]=$v['val'];
			}
			$this->assign('cur_setting',$cur_setting);
			//$this->cur_setting=json_decode($ConfList['config'],true);
			$this->display("Public:siteConf");
		}else{
			$ConfList=$this->dao->alias("s")->join("left join __TEMPLATE__ as t on t.id=s.template_id")->where(array('s.id'=>$this->siteid))->Field("t.config as confList")->find();
			$setting_list=json_decode($ConfList['confList'],true);
			
			
			
			foreach($setting_list as $k=>$v){
				foreach($v['list'] as $key => $val){
					if(isset($_GET['field']) && $_GET['field'] != '' && $val['name'] == $_GET['field']){
						$setting_list[$k]['list'][$key]['on'] = 1;
						$setting_list[$k]['open'] = 1;
						//dump($setting_list[$k]['open']);
					}
				}
			}
			$this->assign('setting_list', $setting_list);
			
			$this->id=isset($_GET['id'])?$this->_get('id'):$this->siteid;
			//多表存储扩展,提高效率
			$this->cur_setting = M('Setting_extends')->where(array('site_id'=>$this->id))->select();
			foreach($this->cur_setting as $k=>$v){
				
				$cur_setting[$v['name']]=$v['val'];
			}
			
			$this->editField = $this->_get('field');
			
			$this->assign('cur_setting',$cur_setting);
			//$this->cur_setting=json_decode($ConfList['config'],true);
			$this->display("Public:siteConf");
		}
	}
	//写入站点配置项值
	public function update_config(){
		if($this->_post('id')){
			$configdb=M('Setting_extends');
			$one=$configdb->where(array('site_id'=>$this->_post('id')))->select();
			foreach($one as $k=>$v){
				$oldData[]=$v['name'];
			}
			//取得原有配置值$one
			$data=$_POST;
			unset($data['site_id']);
			unset($data['id']); //去掉多余的ID号，剩下配置项
			
			foreach($data as $k=>$v){
				$u['name']=$k;
					$u['val']=$v;
					$u['site_id']=$this->_post('id');
				if(in_array($u['name'],$oldData)){
					
					$configdb->where(array('site_id'=>$this->_post('id'),'name'=>$k))->data($u)->save();
				}else{
					$configdb->data($u)->add();
				}
				//dump($configdb->getLastSql());
			}
			$this->success("操作完成");
		}else{
			$this->error("没有提交数据");
		}
	}
	//显示模板列表给用户选择
	public function showTemplateList(){
		$templateModel=M('Template');
		$this->template_group=M('Template_group')->select();
		$this->curSite=$this->dao->where(array('id'=>$this->siteid))->find();
		$curUser=M('User')->where(array('id'=>$this->UserInfo))->find();//查找当前用户信息
		//用户是超级管理员
		$this->listmap=1;
		if($this->_get('groupid')){
			$this->listmap.=" and group_id=".$this->_get('groupid');
			$this->assign('groupid',$this->_get('groupid'));
		}
		
		$this->dao=D('Template');
		parent::_list();

		$this->display('Public:TemplateList');
	}
	//为站点设置模板
	public function setTemplate(){
		$_POST[C('TOKEN_NAME')] = $_SESSION[C('TOKEN_NAME')];
		if($this->_post('template_id')){
			$curTemplate=M('Template')->where(array('id'=>$this->_post('template_id')))->find();
			$curUser=M('User')->where(array('id'=>$this->UserInfo))->find();//查找当前用户信息
			$templateids=explode(',',$curUser['template_id']);
			//判断是否为免费模板,如果不是必须是购买了才能切换
			if($curTemplate['is_free']==0){//非免费 
			    //判断是否已经购买
				
				if(in_array($curTemplate['id'],$templateids)){
					$_POST['id']=$this->siteid;
			        parent::update();
				}else{
					//超级管理员直接切换
					
					if($curUser['isadministrator']){
						$_POST['id']=$this->siteid;
			            parent::update();
					}else{
						//用积分兑换
						if(intval($curUser['score'])>=intval($curTemplate['score'])){
							$_POST['id']=$this->siteid;
							
							//减去积分
							$userData['score']=intval($curUser['score'])-intval($curTemplate['score']);
							$templateids[]=$curTemplate['id'];
							$userData['template_id'] = implode(',',$templateids);
							M('User')->where(array('id'=>$curUser['id']))->save($userData);
			                parent::update();
						}else{
							$result['status']=0;
							$result['info']='您没有足够的积分';
							echo json_encode($result);
							exit();
						}
					}
					
				}
			}else{
				$_POST['id']=$this->siteid;
			    parent::update();
			}
			    
		}
	}
	
	//复制站点
	public function copySite(){
		//页面数量
		if(IS_AJAX){
			$copycount = 0;
			$id = $this->_get('id');
			foreach($this->_get('copydata') as $v){
				$copycount += (int)M($v) -> where(array('site_id' => $id)) -> count();
				
				if($v == 'Pages'){
					$pages = M('Pages') -> where(array('site_id' => $id)) -> Field('id') -> buildSql();
					$copycount += (int)M('Modules') -> where("site_id = '".$id."' and pages_id in(".$pages.")") -> count();
				}
			}
			echo $copycount;
			exit;
		}
		
		D('Site') -> copy();
		if($this->_post('copydata')){
			echo '操作成功！复制操作已经完成！请关闭窗口。';exit;
		}
		$this->display();
	}
	
	public function copy(){
		//计算复制总量
		
		$this->display();
	}
	
	
	
	//选择管理用户
	public function selectUser(){
		$this->listmap = 1;
		
		
		if(!session(C('ADMIN_AUTH_KEY'))){
			$this->listmap .= " and (pid = '".session(C('USER_AUTH_KEY') )."' or id = '".session(C('USER_AUTH_KEY') )."')";
		}
		
		
		
		
		
		
		$this->dao = D('User');
		parent::_list();
		$this->dao = D('Site');
		
		//当前站点
		$this->info = $this->dao -> where(array('id' => $this->_get('id'))) ->find();
		$curUserList = $this->dao ->alias('s') -> join("left join __SITE_USER__ as su on su.site_id = s.id") -> join("left join __USER__ as u on u.id = su.user_id")->Field('u.*,s.id as site_id')->where(array('s.id' => $this->_get('id'),'su.user_id' => array('gt',0))) -> select();
		
		$this->assign('curUserList',$curUserList);
		
		$this->display();
	}
	//添加管理用户
	public function addUser(){
		$this->dao = D('Site_user');
		$data['user_id'] = $this->_post('user_id');
		$data['site_id'] = $this->_post('sid');
		$info = $this->dao -> where($data) -> find();
		if(!is_array($info)){
			
			//$this->dao -> create($data);
			$ret = $this->dao -> add($data);
			if($ret !== false){
				$nickname = M('User') -> where(array('id' => $data['user_id'])) -> find();
				$red['status'] = 1;
				$red['data'] = $nickname['nickname'];
				$red['info'] = '添加成功';
				exit(json_encode($red));
			}else{
				$this->error($this->dao -> getError());
			}
		}else{
			$this->error('已经存在这个用户');
		}
	}
	//删除管理用户
	public function delUser(){
		$this->dao = D('Site_user');
		$data['user_id'] = $this->_post('user_id');
		$data['site_id'] = $this->_post('sid');
		$ret = $this->dao -> where($data) -> delete();
		if($ret !== false){
			$red['status'] = 1;
			$red['data'] = $data['user_id'];
			$red['info'] = '删除成功';
			exit(json_encode($red));
		}else{
			$this->error($this->dao -> getError());
		}
	}
	
	//整理页面和模块
	public function resetPages(){
		if(isset($_GET['id']) && intval($_GET['id']) > 0){
			
			$id = intval($_GET['id']);
			
			$pagesDB = D('Pages');
			$pagesList = $pagesDB -> where(array('site_id' => $id)) -> select();
			//新建模块模型
			$modulesDB = D('Modules');
			//新建导航模型
			$navDB = D('Nav');
			//查询出当前站点所有页面
			foreach($pagesList as $key => $val){
				$modulesDB -> where(array('pages_id' => $val['id'])) -> data(array('site_id' => $val['site_id'])) -> save();
				
				
				//dump($modulesDB -> getLastSql());
				//查找当前页面中所有导航模块
				$navList = $modulesDB -> where(array('pages_id' => $val['id'], 'type' => 9)) -> save();
				foreach($navList as $k => $v){
					$navDB ->  where(array('modules_id' => $v['id'])) -> data(array('site_id' => $val['site_id'])) -> save();
				}
			}
			$this->success('整理完成!',U('index'));
		}else{
			$this->success('error!',U('index'));
		}
	}
	
	
	
	
	
	
	//创建站点续费订单
	public function renew(){
		/*$id = $this->_get('id');
		//找一下这个站点在哪个代理平台下，查找这个代理平台的
		$cursite = $this->dao -> where(array('id' => $id)) -> find();
		if($cursite['agentid'] == 0){
			$this->error('当前产品不支持在线续费，请联系管理员人工续费，谢谢！');exit;
		}
		$agentsite = $this->dao -> where(array('id' => $cursite['agentid'])) -> find();
		//找到这个代理平台了，如果ID存在，而这个平台却不存在，那么平台可能已经被删除，提示平台不存在
		if(!$agentsite){
			$this->error('找不到当前产品的归属平台，请联系管理员处理，谢谢!');
			exit;
		}*/
		//找到当前管理员对应的前端会员，用于记录这个续费订单，以便以后查证,找到这个会员后当即登录这个会员，以便创建订单
		$user = M('User') -> where(array('id' => session(C('USER_AUTH_KEY')))) -> find();
		$id = $this->_get('id');
		$this->siteinfo = M('Site') -> where(array('id' => $id)) -> find();
		
		
		$modules = array ( 'template_id' => '44', 'id' => '1672', 'pages_id' => '114', 'pid' => '0', 'site_id' => '13', 'title' => '自定义模块', 'content' => NULL, 'remark' => NULL, 'dataname' => '', 'listsize' => '5', 'width' => 'auto', 'height' => 'auto', 'borderTop' => 'none', 'borderRight' => 'none', 'borderBottom' => 'none', 'borderLeft' => 'none', 'titleBorderTop' => 'none', 'titleBorderRight' => 'none', 'titleBorderBottom' => 'none', 'titleBorderLeft' => 'none', 'titleHeight' => '35px', 'titleWidth' => '100%', 'titleLineHeight' => '1.5', 'titleBackground' => 'none', 'titleBackgroundColor' => '', 'titleBackgroundImg' => '', 'titleBackgroundRepeat' => 'no-repeat', 'titleBackgroundPosition' => '', 'titlePadding' => '0px 15px', 'titleColor' => '#000', 'titleDisplayMore' => '', 'moreLink' => NULL, 'titleMoreText' => 'more+', 'titleMoreBackground' => NULL, 'titleIsBold' => '1', 'titleFontSize' => '14px', 'listWidth' => '200px', 'listHeight' => '200px', 'listMargin' => '5px', 'listTitleFontSize' => '14px', 'listTitleLineHeight' => '30px', 'listTitleHeight' => '30px', 'listTitleBackground' => 'none', 'listTitleColor' => '#000', 'listTitlePadding' => '0', 'listTitleLength' => '14', 'listTitleHoverColor' => '#f60', 'listTitleAlign' => 'center', 'listContentHeight' => '50px', 'listContentLineHeight' => '24px', 'listContentFontSize' => '14px', 'listContentColor' => '#000', 'listContentLength' => '0', 'listContentIndent' => '2em', 'listContentOut' => '…', 'align' => '', 'margin' => '0 auto 0 auto', 'padding' => '0 0 1em 0', 'style' => '', 'backgroundimage' => '/Public/Uploads/8/Img8-20151102/5636d203d32b8.png', 'backgroundimagesLeft' => NULL, 'backgroundimagesRight' => NULL, 'backgroundrepeat' => 'repeat-x', 'backgroundPosition' => 'center bottom', 'backgroundcolor' => '', 'display_title' => '0', 'display_pages' => '0', 'scrollCount' => '1', 'isTab' => '0', 'picDisplayCount' => '1', 'type' => '0', 'sort' => '4', 'filename' => 'diyContent', 'template_modules_id' => '0', 'templatefilename' => '', 'img_url' => NULL, 'autoPlay' => '1', 'effect' => 'fade', 'interTime' => '5000', 'baidupoint' => NULL, 'position' => 'static', 'displayForm' => '0', 'displayLogo' => '0', 'displayTel' => '0', 'listTitleBackgroundColor' => '#ccc', 'navpar' => '/', 'titleAlign' => 'left', 'extends' => NULL, 'form_id' => '0', 'thumbtype' => '0', 'formAction' => NULL, 'import' => '0', 'diydata' => NULL, 'diysource' => NULL, 'oldid' => '0', );
		$this -> assign('v', $modules);
		$product = array ( 'id' => '1', 'title' => '系统续费', 'remark' => NULL, 'module' => '1', 'en_title' => '', 'content' => NULL, 'attrtext' => NULL, 'en_content' => NULL, 'price' => '0.00', 'originalCost' => '0', 'affmoney' => '0.00', 'discount' => '0.88', 'cost' => '0.00', 'img_url' => '', 'mimg_url' => '', 'is_hot' => '0', 'is_top' => '0', 'is_rec' => '0', 'status' => '1', 'permission' => '-1', 'socre' => '0', 'buy_socre' => '0', 'sort' => '100', 'salecount' => '0', 'out_link' => '', 'table_name' => '2', 'extendsField' => '', 'category_id' => '0', 'brand_id' => '0', 'site_id' => '1', 'stocks' => '0', 'sales' => '0', 'attrList' => NULL, 'create_time' => NULL, 'update_time' => '1453093834', 'supplier_id' => '11', 'shipping_id' => '0', 'weight' => '0.00', 'relateids' => NULL, 'shipping_fee' => '0.00', 'integral_pay' => '0', 'need_shipping' => '1', 'display' => '1', 'limitBuy' => '0', 'affpass' => '0', 'page_title' => NULL, 'description' => NULL, 'area' => NULL, 'noshippingfee' => '0', 'code' => NULL, 'is_cashback' => '0', 'coupon_id' => '0', 'servicecard_id' => '0', 'roleid' => '0', 'levelBuy' => '0', 'minBuy' => '0', 'unit' => NULL, 'autoconfirm' => '0', 'oldid' => '0', 'starttime' => NULL, 'timeout' => NULL, 'systemagent' => '0', 'systemagentprice' => '[{"num":"0","price":"128","aff":"100"}]', 'levelpriceconfig' => NULL, 'numpriceconfig' => NULL, );
		$product['systemagentprice'] = json_decode($this->siteinfo['renewprice'],true);
		
		//dump($product['systemagentprice']);
		$this->assign($product);
		//所有管理者ID，创建一条子语句
		//$userids = M('Site_user') -> where(array('site_id' => $id)) -> Field() -> buildSql();
		//
		$member = M('Member') -> where(array('id' => $user['member_id'])) -> find();
		
		//找到这个会员后使用会员所属站点号登录，登录完成后马上跳转创建订单
		//$member = $this->dao -> where(array('site_id' => $this->siteid, 'id' => $this-> _get('id'))) -> find();dump($member);
		if(!$member){
			/*$this->error('找不到当前产品的所属者，请联系管理员处理，谢谢!');
			exit;*/
		}
		session('memberInfo', $member);
		$this->member = $member;
		$this->display();
		
	}
	
	//异步返回当前站点续费的价格
	public function getSitePriceByNumrenew(){
		$num = $this->_post('num');
		$siteid = $this->_post('siteid');
		$price = M('Site') -> where(array('id' => $siteid)) -> getField('renewprice');
		//$this->price = json_decode($price)); 
		$db = D('Agentprice');
		//记录个数，用COOKIE记录 
		setcookie('siterenew', $siteid.'-'.$num, time() + 3600, '/');
		echo $db -> getprice($price, intval($num));
	}
	
	
	//续费
	public function createreneworder(){
		if(isset($_POST['siteid']) || isset($_COOKIE['siterenew'])){
			$orderDB = D('Order');
			if(isset($_COOKIE['siterenew'])){
				$dataarr = explode('-', $_COOKIE['siterenew']);
				$_POST['siteid'] = $dataarr[0];
				$_POST['num'] = $dataarr[1];
				setcookie('siterenew', NULL, time() - 1, '/');
			}
			if(!$_POST['siteid']){
				return false;
			}
			$Product = M('Site') -> where(array('id' => $_POST['siteid'])) -> find();
			if(!$Product){
				return false;
			}
			$Agentpricedb = D('Agentprice');
			if(intval($_POST['num']) == 0){
				$_POST['num'] = 0;
			}else{
				$_POST['num'] = abs(intval($_POST['num']));
			}
			$price = $Agentpricedb -> getprice($Product['renewprice'], $_POST['num']);
			
			
			$aff = $Agentpricedb -> getaff($Product['renewprice'], $_POST['num']);
			
			
			$_POST['is_renew'] = $Product['id'];
			$_POST['site_id'] = $Product['agentid'];
			$_POST['relate_id'] = $Product['agentid'];
			$_POST['status'] = 1;//0.已取消 1.待支付 2.已支付
			$_POST['ordernumber'] = build_order_no();
			$_POST['create_time'] = time();
			$_POST['create_date'] = strtotime(date('Y-m-d'));
			//$_POST[C('TOKEN_ON')] = $_POST[C('TOKEN_ON')];
			$_POST['total'] = $price;
			
			$_POST['member_id'] = $Product['member_id'];
			$_POST['pay_type'] = isset($_POST['pay_type'])?$_POST['pay_type']:'';
			if($_POST['num'] > 0){
			    $_POST['Guestbook'] = '续费【'.$Product['title'].'】【'.$_POST['num'].'个月】';
			}else{
				$_POST['Guestbook'] = '续费【'.$Product['title'].'】【终身版】';
			}
			$membersaledb = M('Membermembersale');
            //$_POST['is_renew'] = $_POST['is_renew'];
			$member_memberdb = M('Member_member');
			//$orderDB->create();
			$orderId = $orderDB->add($_POST);
			if($orderId){ 
				//写入订单明细
				$saledb = M('Sale');
				$saledata = array();
				$saledata['order_id'] = $orderId;
				$saledata['product_id'] = 0;
				$saledata['member_id'] = $_POST['member_id'];
				$saledata['num'] = $_POST['num'] == 0 ? 1 : $_POST['num'];
				$saledata['site_id'] = __SITEID__;
				$saledata['price'] = $price;
				$saledata['aff_money'] = $aff * $saledata['num'];
				$saledata['total'] = $_POST['total'] * $saledata['num'];
				$saledata['attr'] = '';
				$saledata['title'] = '站点续费';
				$saledata['img_url'] = '/createsite.jpg';
				$saledata['supplier_id'] = 0;
				$saledata['code'] = $v['code'];
				$sale_id = $saledb -> data($saledata) -> add();
				
				
				
				//写入销售记录与推荐人关系表
					//下单的人所有上家
					$memberpids = $member_memberdb -> where(array('smember_id' => $saledata['member_id'])) -> select();
					foreach($memberpids as $mk => $mv){
						$membersale['order_id'] = $orderId;
						$membersale['site_id'] = __SITEID__;
						$membersale['sale_id'] = $sale_id;
						$membersale['product_id'] = 0;
						$membersale['dateline'] = $_POST['create_time'];
						$membersale['member_id'] = $mv['member_id'];
						$membersale['deep'] = $mv['deep'];
						$membersale['price'] = $saledata['price'];
						$membersale['aff_money'] = $saledata['aff_money'];
						$membersale['num'] = $saledata['num'];
						$membersale['total'] = $saledata['total'];
						
						$membersaledb -> add($membersale); 
					}
				
				
				
				
				
				if($_POST['total'] == 0){
					D('Order') -> upstate($_POST['ordernumber']); 
				    redirect(U('Payment/index', array('id' => $orderId)));
				}
				C('URL_MODEL',0);
				redirect(U('Home/Payment/index', array('id' => $orderId),true,false,true,$Product['agentid']));
			}else{
				$this->error($orderDB->getError());
			}
		}else{
			$list = M('Site') -> where(array('price' => array('neq', ''))) -> select();
			$this->assign('list', $list);
			$this->display();
		}
	}
}
